import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { actionCreators } from './store';
import { Select,Layout,Form,Modal, Table, Input, Button, InputNumber, Popconfirm,Dropdown,Menu} from 'antd';
import {changeSubNum} from '../../../api/config/config'

import './style.scss';

const { Content } = Layout;
const { Column } = Table;

@withRouter
class resourceType extends Component{
  state={
    page: 10,
    searchValue: '',
    typeEditorVisible:false,
    recordData:{},
    typeAddVisible:false,
    sourceArr:[],
    supNumberArr:[],
    sendNumber:0,
    subNumber:0,
    currentPage:1
  };

 /*  changePage = (value) => {
    this.setState({page:value});
  }
  
  setSearchValue = (e) => {
    this.setState({searchValue: e.target.value})
  }

  handleSearch = () => {
    let userName = "admin";//待修改
    this.props.searchApi(userName,this.state.searchValue)
  }

  resetSearch = () => {
    this.setState({searchValue:''});
    let userName = "admin";//待修改
    this.props.getConfig(userName);
  }

  deleteCon = (record) => {
    let databaseConfig = JSON.parse(record.userDatabaseConfig);
    let params = {databaseId: databaseConfig.databaseId,id: databaseConfig.id};
    this.props.deleteCon(params);
  } */
  editRef=React.createRef();
  addRef=React.createRef();
    //切换停用启用
  toggleStatus=(record)=>{
    const enable=record.isEnable;
    const number=record.number
    if(enable===0){
      //启用
      this.props.startTypeEnable(number);
  }
  else{
      //禁用
      this.props.noTypeEnable(number);
  }
  };
//点击编辑
editor=(record)=>{
    this.setState({
      recordData:record,
      typeEditorVisible:true
    })
}
//取消编辑
editorCancel=()=>{
  this.setState({
    typeEditorVisible:false
  })
}
//保存编辑
editorType=()=>{
  this.editRef.current.validateFields().then(values=>{
    console.log(values);
    if(values){
      const editValue={
        name:values.name,
        number: values.number,
        description:values.description===undefined?'':values.description
      };
      this.props.saveEdit(editValue);
      this.editorCancel();
    }
  })
}
//删除项
deleteCon = (record) => {
  const number=record.number
  this.props.deleteItem(number);
}
//保存添加
saveAddType=()=>{
    this.addRef.current.validateFields().then(value=>{
            console.log(value);
            if(value){
              const addValue={
                description:value.description===undefined?'':value.description,
                name:value.name,
                number:value.number,
                superNumber:value.superNumber,
              }
              this.props.addType(addValue);
              this.addCancel();
            }
    })
}
//点击新增
addItem=()=>{
  this.setState({
    typeAddVisible:true
  });
  const sourceArr=[];
  const supNumberArr=[];
  console.log(this.props.allResource)
    this.props.allResource.forEach(item=>{
      const itemName=item.name;
      const itemNumber=item.number;
      sourceArr.push(itemName);
      supNumberArr.push(itemNumber)
    });
    this.setState({
      sourceArr,
      supNumberArr
    })
}
//退出新增
addCancel=()=>{
 this.setState({
  typeAddVisible:false
 })
}
//根据上级名称修改上级代码和下级代码
sendSubNumber=(type)=>{
  const index=this.state.sourceArr.indexOf(type);
  const sendNumber=this.state.supNumberArr[index];
  const token=localStorage.getItem('Token');
  changeSubNum(token,sendNumber).then(res=>{
       const subNumber=res.data.data;
    this.setState({
    sendNumber,
    subNumber
  },()=>{
    if(this.addRef.current===null)return;
    this.addRef.current.setFieldsValue({superNumber:this.state.sendNumber});
    this.addRef.current.setFieldsValue({number:this.state.subNumber})
  })
  })

}
//修改inputNUmber页码
changePage=(e)=>{
    this.setState({
      currentPage:e
    })
}
//修改表格页码
changePageNum=(current)=>{
    this.setState({
      currentPage:current
    })
}
//授权
impower=(record)=>{
/*   console.log(record);
  const number=record.number;
  console.log(record); */
  this.setState({
    recordData:record
  })
}
//授权下拉菜单
selectOrg=(item)=>{
  /* console.log(item); */
  let orgId;
  const number=this.state.recordData.number;
  console.log(this.state.recordData);
  console.log(this.props.orgIdArr);
  this.props.orgIdArr.forEach(ele=>{
    if(ele.name===item.key){
        orgId=ele.id
    }
  })
   this.props.impower(number,orgId) 

}
componentWillMount(){
  let userLevel=localStorage.getItem('userLevel');
    if((!userLevel)||(!userLevel==='0')){
      this.props.history.push('/login')
    };
}
  componentDidMount(){
    let userName = "admin";//待修改
    this.props.getAllType();
    this.props.getSupSelect();
    this.props.getAllOrg();
  };

  render(){
    const { currentPage ,typeEditorVisible,recordData,typeAddVisible,sourceArr,supNumberArr} = this.state;
    const {typePageNum,orgIdArr}=this.props;
    const sourceTypeArr=[];
    const supNumber=[];
    sourceArr.forEach(item=>{
      sourceTypeArr.push(
        <Select.Option key={item} value={item}>
        {item}
      </Select.Option>
      )
    });
    supNumberArr.forEach(item=>{
       supNumber.push(
        <Select.Option key={item} value={item}>
        {item}
      </Select.Option>
       )
    })
    const paginationProps = {
      onChange: (current) => {
        this.changePageNum(current);
      },
      current: currentPage,
      hideOnSinglePage: true,
      pageSize: 10,
      showSizeChanger: false,
    };
    const limitDecimals = (value) => {
      if (typeof value === "number") {
        return value;
      }
      if (typeof value !== "number") {
        if (value > typePageNum) {
          return value.replace(/^\d+/g, typePageNum);
        }
        return value.replace(/^(0+)|[^\d]+/g, "");
      }
    };
    const impowerOrgArr=[];
    const impowerIdArr=[];
    orgIdArr.forEach(item=>{
      const org=item.name;
      const id=item.id;
           impowerOrgArr.push(org);
           impowerIdArr.push(id);
    })
    const menuStyle={
      height:'100px',
      overflowY:'scroll'
    }
    const menu=(
      <Menu style={menuStyle} onClick={this.selectOrg}>
        {
          impowerOrgArr.map(item=>{
            return <Menu.Item key={item}>{item}</Menu.Item>
          })
        }
    </Menu>
    )
    return (
      <Content style={{marginTop:12}}>
        <div style={{fontWeight: 'bold'}}>资源分类管理
        <Button onClick={this.addItem} style={{ float: "right" }}>新增</Button>
        </div>
        <div className="table-box" style={{marginTop:24}}>
          <Table 
          rowKey="number"
          pagination={paginationProps}
          dataSource={this.props.resourceType}>
            <Column title="序号" render={(text,render,index)=> {return (currentPage - 1) * 10 + index + 1;}}/>
            <Column title="编码" dataIndex="number" key="number"/>
            <Column title="分类" dataIndex="type" key="type"  render={(text,record)=><span>{record.type===3?'项':''}</span>}/>
            <Column title="名称" dataIndex="name" key="name"/>
            <Column title="创建时间" dataIndex="createTime" key="createTime"/>
            <Column title="状态" dataIndex="isEnable" key="isEnable"  render={(text,record)=><span>{record.isEnable===0?'启用':'停用'}</span>}/>
            <Column title="操作" dataIndex="operation" key="operation"
            render={(text,record)=>(
              <span>
                <span className="action" onClick={()=>{this.toggleStatus(record)}}>{record.isEnable===0?'停用':'启用'}</span>
                <Dropdown overlay={menu} placement="bottomCenter">
    <a className="ant-dropdown-link" onClick={e => e.preventDefault()}><span className="action" onMouseOver={()=>this.impower(record)}>授权</span></a>
  </Dropdown>
                <span className="action" onClick={()=>{this.editor(record)}}>编辑</span>
                <Popconfirm
                title="确认删除?"
                onConfirm={() => this.deleteCon(record)}
                >
                  <span className="action">删除</span>
                </Popconfirm>
              </span>)}/>
          </Table>
          <div 
          className={this.props.typePageNum>1?'footer':'withoutPagination'}
          >
            显示<InputNumber 
             min={1}
             formatter={limitDecimals}
             parser={limitDecimals}
             max={typePageNum}
             defaultValue={1}
             value={currentPage}
             onChange={e=>this.changePage(e)} 
            />项结果，共{typePageNum}项
          </div>
        </div>
        <Modal
            destroyOnClose
            title={<div className="title-Style">编辑项信息</div>}
            visible={typeEditorVisible}
            onCancel={this.editorCancel}
            maskClosable={false}
            bodyStyle={{ backgroundColor: "#f0f3f6" }}
            footer={
              <div className="footer-Style">
                <Button
                  type="primary"
                  style={{ color: "white", borderRadius: 5 }}
                  onClick={this.editorType}
                >
                  保存
                </Button>
                <Button
                  style={{ color: "#007cdb", borderRadius: 5 }}
                  onClick={this.editorCancel}
                >
                  取消
                </Button>
              </div>
            }
          >
            <Form
              labelCol={{ span: 24 }}
              wrapperCol={{ span: 20 }}
              ref={this.editRef}
            >
            <Form.Item
                label={<span className="formItemStyle">名称</span>}
                rules={[{ required: true, message: "请输入名称" },]}
                initialValue={recordData.name}
                name="name"
                                >
             <Input autoComplete="off" />
             </Form.Item>
             <Form.Item
                     label={<span className="formItemStyle">编码</span>}
                     initialValue={recordData.number}
                       rules={[
                        { required: true, message: "请输入编码" },
                          ]}
                                    name="number"
                          >
                                    <Input autoComplete="off" />
                   </Form.Item>
                   <Form.Item
                                label={<span className="formItemStyle">备注</span>}
                                name="description"
                            >
                                <Input.TextArea placeholder="请输入备注" />
                            </Form.Item>
            </Form>
          </Modal>
          <Modal
            destroyOnClose
            title={<div className="title-Style">新增资源分类</div>}
            visible={typeAddVisible}
            onCancel={this.addCancel}
            maskClosable={false}
            bodyStyle={{ backgroundColor: "#f0f3f6" }}
            footer={
              <div className="footer-Style">
                <Button
                  type="primary"
                  style={{ color: "white", borderRadius: 5 }}
                  onClick={this.saveAddType}
                >
                  添加
                </Button>
                <Button
                  style={{ color: "#007cdb", borderRadius: 5 }}
                  onClick={this.addCancel}
                >
                  取消
                </Button>
              </div>
            }
          >
            <Form
              labelCol={{ span: 24 }}
              wrapperCol={{ span: 20 }}
              ref={this.addRef}
            >
            <Form.Item
                label={<span className="formItemStyle">上级名称</span>}
                rules={[{ required: true, message: "请选择上级名称" },]}
                initialValue={'请选择上级名称'}
                name="superName" >
             <Select
                    onChange={(e)=>{
                      this.sendSubNumber(e);
                    }}
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  >
                     {sourceTypeArr}
                  </Select>
             </Form.Item>
             <Form.Item
                     label={<span className="formItemStyle">名称</span>}
                       rules={[
                        { required: true, message: "请输入名称" },
                          ]}
                                    name="name"
                          >
                                    <Input autoComplete="off" />
                   </Form.Item>
                   <Form.Item
                label={<span className="formItemStyle">上级代码</span>}
                rules={[{ required: true, message: "请选择上级代码" },]}
                /* initialValue={recordData.name} */
                name="superNumber"
                                >
             <Select
             disabled
             getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  >
                    {supNumber}
                  </Select>
             </Form.Item>
             <Form.Item
                label={<span className="formItemStyle">代码</span>}
                rules={[{ required: true, message: "请选择代码" },]}
                /* initialValue={recordData.name} */
                name="number"
                                >
             <Select
             disabled
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  >
                    {/* {typearr} */}
                  </Select>
             </Form.Item>
                   <Form.Item
                                label={<span className="formItemStyle">备注</span>}
                                name="description"
                            >
                                <Input.TextArea placeholder="请输入备注" />
                            </Form.Item>
            </Form>
          </Modal>
      </Content>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    resourceType: state.getIn(['type','resourceType']),
    allResource:state.getIn(['type','allResource']),
    subNumber:state.getIn(['type','subNumber']),
    typePageNum:state.getIn(['type','typePageNum']),
    orgIdArr:state.getIn(['type','orgIdArr'])
  }
}

const mapDispatchToProps = (dispatch) => ({
  // getConfig(userName){
  //   dispatch(actionCreators.getAllConfigOperation(userName));
  // },
  getAllType(){
    dispatch(actionCreators.getAllType())
  },
  startTypeEnable(number){
    dispatch(actionCreators.startTypeEnable(number))
  },
  noTypeEnable(number){
    dispatch(actionCreators.noTypeEnable(number))
  },
  impower(number,orgId){
    dispatch(actionCreators.typeImpower(number,orgId))
  },
  saveEdit(editValue){
    dispatch(actionCreators.saveEdit(editValue))
  },
  deleteItem(number){
    dispatch(actionCreators.deleteItem(number))
  },
  getSupSelect(){
    dispatch(actionCreators.getSupSelect())
  },
  addType(addValue){
    dispatch(actionCreators.addType(addValue))
  },
  getAllOrg(){
    dispatch(actionCreators.getAllOrg());
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(resourceType);